package Controller.SCServlet;

import Dao.SCDao;
import bean.SC;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/sc_add")
public class sc_add extends HttpServlet {
    SCDao scDao = new SCDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String sc_sno = req.getParameter("sno");
        String sc_cno = req.getParameter("cno");

        ArrayList<SC> scList = scDao.selectAll();
        SC sc = new SC();
        sc.setSno(sc_sno);
        sc.setCno(sc_cno);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        if (scList.contains(sc)) {
            map.put("code", 400);
            map.put("msg", "该课程已选");
        } else {
            scDao.insert(sc_sno, sc_cno);
            map.put("msg", "选课成功");
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }
}
